<template>
	<!-- 我的-康复顾问-康复师详情 -->
	<!-- 新增状态 -->
	<view class="content">
		<view class="bg"></view>
		<view style="margin-top: 30rpx;z-index: 100;">
			<view class="tab">
				<view class="tab-item" v-for="(item,index) in list" :class="{active:activeTab==item.title}" @click="change(item)">
					<view class="title">{{item.title}}</view>
					<view class="line"></view>
				</view>
			</view>
			<view class="info-content">
				<view class="info-item">
					<view class="key">姓名</view>
					<uni-easyinput v-model="baseFormData.name" placeholder="请输入姓名" :styles="{borderColor: '#fff'}" />
				</view>
				<view class="info-item">
					<view class="key">身份证号</view>
					<!-- <view>{{ getAge(baseFormData.idnumber)}}</view> -->
					<uni-easyinput v-model="baseFormData.idnumber" placeholder="请输入身份证号" :styles="{borderColor: '#fff'}" />
				</view>
				<!-- 				<view class="info-item">
					<view class="key">性别</view>
					<view>{{ gender }}</view>
				</view>
				<view class="info-item">
					<view class="key">年龄</view>
					<view>{{ age }}</view>
				</view> -->
				<view class="info-item">
					<view class="key">手机号</view>
					<uni-easyinput v-model="baseFormData.mobileTel" placeholder="请输入手机号" :styles="{borderColor: '#fff'}" />
				</view>
				<view class="info-item">
					<view class="key">资质</view>
					<uni-data-select style="width:45%;" :clear="false" v-model="baseFormData.level" :localdata="range2"></uni-data-select>
				</view>
				<view class="info-item">
					<view class="key">所属门店</view>
					<uni-data-select style="width:45%;" :clear="false" v-model="baseFormData.siteId" :localdata="siteList" @change="change"></uni-data-select>
					<!-- <uni-easyinput v-model="baseFormData.siteName" placeholder="请输入门店" :styles="{borderColor: '#fff'}" /> -->
				</view>
			</view>
		</view>
		<view style="display: flex;align-items: center;justify-content: center;position: fixed;
		bottom: 0rpx;">
			<view class="btn-cancel" @click="cancel()">取消</view>
			<view class="btn-save" @click="save()">保存</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				level: {
					"1": "初级康复师",
					"2": "中级康复师",
					"3": "高级康复师"

				},
				range: [{
						value: "男",
						text: "男"
					},
					{
						value: "女",
						text: "女"
					},
				],
				range2: [{
						value: "1",
						text: "初级康复师"
					},
					{
						value: "2",
						text: "中级康复师"
					},
					{
						value: "3",
						text: "高级康复师"
					},
				],
				baseFormData: {},
				isedit: false,
				activeTab: "基本资料",
				list: [{
						title: "基本资料"
					},
					// {
					// 	title: "其他资料"
					// },
				],
				siteName: "",
				siteId: 0,
				siteList: [],
			}
		},
		onLoad(option) {
			// this.adviserDetail();
			this.getSiteList();
		},
		methods: {
			change(item) {
				alert(JSON.stringify(item));
			},
			cancel() {
				uni.navigateBack({
					delta: 1
				});
			},
			getSiteList() {
				let that = this;
				uni.request({
					url: "https://guokang365.mordo-care.com/api/site/searchListAll",
					method: 'POST',
					//仅为示例，并非真实接口地址。
					header: {
						'Cookie': "JSESSIONID=" + getApp().globalData.serverSession
					},
					data: {
						"orders":[{
						        "column":"id",
						        "type":"desc",
						    }],
					},
					success: (res) => {
						// todo 入参是or
						console.log(JSON.stringify(res.data))
						if (res.data.result != '100') {
							// 获取会员统计数据失败，不确定是否要弹窗
						} else {
							// todo 展示列表
							that.siteList = res.data.list.map(item => ({
								text: item.name,
								value: item.id
							}))
						}
					},
				});
			},
			validateIdCard(idCard) {
				// 只包含数字、大小写字母和xX字符，并且长度为15或18位
				const regExp = /^[0-9a-zA-Z]{15}$|^[0-9a-zA-Z]{18}$|^[0-9a-zA-Z]{17}[xX]$/;

				if (!regExp.test(idCard)) {
					return false;
				}

				// 校验省份信息，只能是已知的省份
				const provinceCode = idCard.substring(0, 2);
				const provinceList = ['11', '12', '13', '14', '15', '21', '22', '23', '31', '32', '33', '34', '35', '36', '37', '41', '42', '43', '44', '45', '46', '50', '51', '52', '53', '54', '61', '62', '63', '64', '65', '71', '81', '82'];
				if (!provinceList.includes(provinceCode)) {
					return false;
				}

				// 校验出生日期信息，需满足年月日格式以及合法性
				const birthStr = idCard.substring(6, 14);
				const year = birthStr.substring(0, 4);
				const month = birthStr.substring(4, 6);
				const day = birthStr.substring(6, 8);
				const birthDate = new Date(`${year}-${month}-${day}`);
				if (birthDate.getFullYear() !== parseInt(year) || birthDate.getMonth() + 1 !== parseInt(month) || birthDate.getDate() !== parseInt(day)) {
					return false;
				}

				// 校验校验码信息，需满足规则
				const checkCode = idCard.substring(17, 18);
				let sum = 0;
				const coefficientList = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
				const checkCodeList = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
				for (let i = 0; i < 17; i++) {
					sum += parseInt(idCard.charAt(i)) * coefficientList[i];
				}
				const modValue = sum % 11;
				return checkCode.toUpperCase() === checkCodeList[modValue];
			},
			getBirthdayByIdCard(idCard) {
				if (idCard == null || idCard == "") {
					return "";
				}
				// 获取出生年月日
				const birthYear = idCard.substr(6, 4);
				const birthMonth = idCard.substr(10, 2);
				const birthDay = idCard.substr(12, 2);
			
				// 构造出生日期对象
				const birthDate = birthYear + "-" + birthMonth + "-" + birthDay;
			
				// 转换为年龄并返回
				return birthDate;
			},
			getAge(idCard) {
				if (idCard == null || idCard == "") {
					return 0;
				}
				// 获取出生年月日
				const birthYear = idCard.substr(6, 4);
				const birthMonth = idCard.substr(10, 2);
				const birthDay = idCard.substr(12, 2);

				// 构造出生日期对象
				const birthDate = new Date(`${birthYear}-${birthMonth}-${birthDay}`);

				// 获取当前日期对象
				const currentDate = new Date();

				// 计算出生日期到当前日期的毫秒数
				const diffTime = currentDate.getTime() - birthDate.getTime();

				// 转换为年龄并返回
				return Math.floor(diffTime / (365 * 24 * 60 * 60 * 1000));
			},
			getGenderByIdCard(idCard) {
				let genderCode = idCard.substring(16, 17);
				return parseInt(genderCode) % 2 === 1 ? '男' : '女';
			},
			save() {
				let that = this;
				// todo 门店需要做成下拉，创建的时候需要传siteId和siteName
				if (that.baseFormData.name == null || that.baseFormData.name == "") {
					uni.showModal({
						content: '请正确填写姓名',
						showCancel: false,
						buttonText: '确定',
					})
				} else if (that.baseFormData.mobileTel == null || that.baseFormData.mobileTel == "") {
					uni.showModal({
						content: '请正确填写手机号',
						showCancel: false,
						buttonText: '确定',
					})
				} else if (that.baseFormData.level == null || that.baseFormData.level == "") {
					uni.showModal({
						content: '请正确选择资质等级',
						showCancel: false,
						buttonText: '确定',
					})
				} else if (that.baseFormData.idnumber == null || that.baseFormData.idnumber == "" || !that.validateIdCard(that.baseFormData.idnumber)) {
					uni.showModal({
						content: '请正确填写身份证',
						showCancel: false,
						buttonText: '确定',
					})
				} else if (that.baseFormData.siteId == null || that.baseFormData.siteId == 0) {
					uni.showModal({
						content: '请正确选择所属门店',
						showCancel: false,
						buttonText: '确定',
					})
				}
				that.baseFormData.age = that.getAge(that.baseFormData.idnumber);
				that.baseFormData.gender = that.getGenderByIdCard(that.baseFormData.idnumber);
				that.baseFormData.birthdate = that.getBirthdayByIdCard(that.baseFormData.idnumber);
				that.baseFormData.recureAdviserId = getApp().globalData.recureAdviserId;
				that.baseFormData.recureAdviserName = getApp().globalData.adviserName;
				// todo 门店需要做成下拉，创建的时候需要传siteId和siteName
				// that.baseFormData.siteId = 1;
				// that.baseFormData.siteName = "互联网门店";
				that.baseFormData.siteName = that.getTextByValue(that.baseFormData.siteId);
				that.baseFormData.mainPhoto = "/static/logo.png";

				uni.request({
					url: "https://guokang365.mordo-care.com/api/recureTeacher/create",
					method: 'POST',
					//仅为示例，并非真实接口地址。
					header: {
						'Cookie': "JSESSIONID=" + getApp().globalData.serverSession
						// 'JSESSIONID': getApp().globalData.serverSession //自定义请求头信息
					},
					data: that.baseFormData,
					success: (res) => {
						// todo 需要使用级联查询，查套餐名
						if (res.data.result != '100') {
							uni.showModal({
								content: '创建失败',
								showCancel: false,
								buttonText: '确定',
							})

						} else {
							uni.showModal({
								content: '创建成功',
								showCancel: false,
								buttonText: '确定',
							})
							that.returnLastPage();
						}
					},
				});
			},
			returnLastPage() {
				//获取页面栈数据
				const pages = getCurrentPages()
				//当长度为1时，则是打开小程序时首先进来的页面，没有上一页
				if (pages.length <= 1) {
					// uni.switchTab({
					// 	url: '/pages/home/home'
					// })
				} else {
					//存上一页信息
					let prevPage = ''
					//存上一页完整路由
					let prevRoute = ''
					//pages的长度-2为上一页，pages最后一个元素则是当前页
					if (pages.length >= 2) {
						prevPage = pages[pages.length - 2]
						prevRoute = prevPage.route
					}
					//返回上一页并触发上一页的刷新方法，加个定时器的原因：降低返回时调用刷新函数失败几率
					setTimeout(() => {
						uni.navigateBack({
							delta: 1,
							success: (event) => {
								//判断是否为刷新数据的目标页
								if (prevRoute.indexOf('pages/my/rehabilitation-list') > -1) {
									prevPage.$vm.reLoadFn()
								}
							}
						});
					}, 300)
				}
			},
			getTextByValue(value) {
				const option = this.siteList.find(item => item.value === value);
				return option ? option.text : '';
			},
			adviserDetail() {
				let that = this;
				uni.request({
					url: "https://guokang365.mordo-care.com/api/recureAdviser/find/" + getApp().globalData.recureAdviserId,
					method: 'GET',
					//仅为示例，并非真实接口地址。
					header: {
						'Cookie': "JSESSIONID=" + getApp().globalData.serverSession
					},
					success: (res) => {
						if (res.data.result != '100') {
							// 获取会员详情失败，不确定是否要弹窗
						} else {
							that.siteName = res.data.entity.siteName;
							that.siteId = res.data.entity.siteId;
						}
					},
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.bg {
		width: 750rpx;
		height: 128rpx;
		background: #CBFFDB;
		filter: blur(25px);
		position: absolute;
		z-index: 1;
		top: 0px;
	}

	.tab {
		display: flex;
		justify-content: space-around;

		// width: 550rpx;
		.tab-item {
			display: flex;
			flex-direction: column;
			align-items: center;
		}

		.title {
			height: 44rpx;
			font-size: 31rpx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 600;
			color: #585858;
			line-height: 44rpx;
		}

		.line {
			width: 37rpx;
			height: 6rpx;
			background: transparent;
			border-radius: 3rpx;
			margin-top: 10rpx;
		}

		.active {
			.line {
				background: #42AE49;
			}

			.title {
				color: #42AE49;
			}
		}
	}

	.info-content {
		box-sizing: border-box;
		width: 707rpx;
		padding: 0 34rpx;
		background: #FFFFFF;
		border-radius: 22rpx;
		margin-top: 30rpx;
	}

	.info-item {
		justify-content: space-between;
		flex-direction: row;
		display: flex;
		font-size: 28rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #393939;
		align-items: center;
		height: 100rpx;
	}

	.key {
		width: 360rpx;
	}

	.btn {
		position: fixed;
		bottom: 0rpx;
		text-align: center;
		width: 750rpx;
		height: 129rpx;
		background: #42AE49;
		font-size: 30rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #FFFFFF;
		line-height: 129rpx;
	}

	.btn-cancel {
		width: 375rpx;
		height: 129rpx;
		background: #D1D1D1;
		font-size: 30rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #525252;
		line-height: 129rpx;
		text-align: center;
	}

	.btn-save {
		width: 375rpx;
		height: 129rpx;
		background: #42AE49;
		font-size: 30rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #FFFFFF;
		line-height: 120rpx;
		text-align: center;
	}
</style>